﻿/*++

Copyright (c) 2011 Rainr Corporation

Module Name:

	Rainr.Utilities.CardUtility

Abstract:

	生成卡片(身份证)号码，验证卡片号码

Author:

	Zhou Junyu (Rainr)    2011-01-12

--*/

using System;
using System.Text;

namespace Rainr.Utilities
{
    /// <summary>
    /// 身份证号码工具类
    /// </summary>
    public static class CardUtility
    {
        /// <summary>
        /// 中国身份证号码15转为18位
        /// </summary>
        /// <param name="cardId15">15位有效身份证号</param>
        /// <returns>转换完成的18位身份证号码</returns>
        public static string CNCard15To18(string cardId15)
        {
            int iS = 0;
            //加权因子常数 
            int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            //校验码常数 
            string LastCode = "10X98765432";
            //新身份证号 
            StringBuilder cardIDNew = new StringBuilder(cardId15.Substring(0, 6));
            //填在第6位及第7位上填上‘1’，‘9’两个数字 
            cardIDNew.AppendFormat("{0}{1}", "19", cardId15.Substring(6, 9));
            string cardtmp = cardIDNew.ToString();
            //进行加权求和 
            for (int i = 0; i < 17; i++)
            {
                iS += int.Parse(cardtmp.Substring(i, 1)) * iW[i];
            }
            //取模运算，得到模值 
            int iY = iS % 11;
            //从LastCode中取得以模为索引号的值，加到身份证的最后一位，即为新身份证号。 
            cardIDNew.Append(LastCode.Substring(iY, 1));
            return cardIDNew.ToString();
        }
        /// <summary>
        /// 中国身份证号码18位转为15位
        /// </summary>
        /// <param name="cardId18">18位身份证号</param>
        /// <returns>转换之后的15位身份证号</returns>
        public static string CNCard18To15(string cardId18)
        {
            StringBuilder sb = new StringBuilder(cardId18);
            sb.Remove(cardId18.Length - 1, 1);
            sb.Remove(6, 2);
            return sb.ToString();
        }
        /// <summary>
        /// 验证中国18位身份证正确是否
        /// </summary>
        /// <param name="cardId18">18位身份证号</param>
        /// <returns>验证结果</returns>
        public static bool CheckCNCard18(string cardId18)
        {
            if (cardId18 == null || cardId18.Length < 18) return false;
            string LastCode = "10X98765432";
            int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            int iS = 0;
            for (int i = 0; i < 17; i++)
            {
                iS += int.Parse(cardId18.Substring(i, 1)) * iW[i];
            }
            int iY = iS % 11;
            return (LastCode.Substring(iY, 1) == cardId18.Substring(17, 1));
        }
    }
}
